package one.bugu.android.demon.ui.activity.shop;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.juefeng.android.framework.LKUtil;
import com.juefeng.android.framework.common.util.ToastUtils;
import com.juefeng.android.framework.view.annotation.LKContentView;
import com.juefeng.android.framework.view.annotation.LKInjectView;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import one.bugu.android.demon.R;
import one.bugu.android.demon.bean.MagicCalBuyBean;
import one.bugu.android.demon.bean.MagicCalDetailBean;
import one.bugu.android.demon.bean.MagicCalShopBean;
import one.bugu.android.demon.common.BaseHttpAsycResponceHandler;
import one.bugu.android.demon.common.MyBaseActivity;
import one.bugu.android.demon.constant.Constant;
import one.bugu.android.demon.constant.HttpConstant;
import one.bugu.android.demon.ui.activity.WebActivity;
import one.bugu.android.demon.ui.activity.wallet.BGTActivity;
import one.bugu.android.demon.ui.dialog.DialogHint;
import one.bugu.android.demon.ui.widget.BaseTopBarView;
import one.bugu.android.demon.util.CodeUtils;
import one.bugu.android.demon.util.DateUtils;
import one.bugu.android.demon.util.IntentUtils;
import one.bugu.android.demon.util.MyTextUtils;
import one.bugu.android.demon.util.OnViewClickListener;
import one.bugu.android.demon.util.ParamUtils;
import one.bugu.android.demon.util.PreferencesUtil;
import one.bugu.android.demon.util.StatusBarUtils;

/**
 * 订单确认
 */
@LKContentView(R.layout.activity_order_affirm)
public class OrderAffirmActivity extends MyBaseActivity {
    /**
     * topBar
     */
    @LKInjectView(R.id.btbv_qp_top_bar)
    private BaseTopBarView btbv_qp_top_bar;
    /**
     * 魔力图片
     */
    @LKInjectView(R.id.iv_oa_icon)
    private ImageView iv_oa_icon;
    /**
     * 商品标题
     */
    @LKInjectView(R.id.tv_oa_give)
    private TextView tv_oa_give;

    /**
     * 商品标题
     */
    @LKInjectView(R.id.tv_oa_title)
    private TextView tv_oa_title;

    /**
     * 商品有效期
     */
    @LKInjectView(R.id.tv_oa_indate)
    private TextView tv_oa_indate;

    /**
     * 魔力值
     */
    @LKInjectView(R.id.tv_os_cal_num)
    private TextView tv_os_cal_num;

    /**
     * 有效期
     */
    @LKInjectView(R.id.tv_oa_indate_time)
    private TextView tv_oa_indate_time;

    /**
     * BGT数量
     */
    @LKInjectView(R.id.tv_oa_bgt)
    private TextView tv_oa_bgt;

    /**
     * BGT赠送数量
     */
    @LKInjectView(R.id.tv_oa_give_bgt)
    private TextView tv_oa_give_bgt;

    /**
     * 价格
     */
    @LKInjectView(R.id.tv_oa_price)
    private TextView tv_oa_price;

    /**
     * 确认按钮
     */
    @LKInjectView(R.id.tv_oa_affirm)
    private TextView tv_oa_affirm;

    private String errorMsg = null;

    private DecimalFormat df = new DecimalFormat("###");

    private String token;

    private MagicCalBuyBean buyData;
    private MagicCalShopBean mgcData;

    /**
     * 弹框
     */
    private DialogHint dialogHint;

    @Override
    protected void initView() {
        super.initView();
        //状态栏
        StatusBarUtils.getInstance().setStatusBar("#FFFFFF", OrderAffirmActivity.this, btbv_qp_top_bar, false);
        //ETH不足弹框文字设置
        dialogHint = new DialogHint(this, "", true);
    }

    @Override
    protected void initData() {
        super.initData();
        mgcData = (MagicCalShopBean) getIntent().getSerializableExtra("MGC_DATA");
        setViewData(mgcData);
        token = PreferencesUtil.getInstance().getString(OrderAffirmActivity.this, Constant.TOKEN);
        getData();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        //topBar事件处理
        btbv_qp_top_bar.setEventInterface(new BaseTopBarView.EventInterface() {
            @Override
            public void leftOnClick() {
                finish();
            }

            @Override
            public void leftCloseClick() {

            }

            @Override
            public void rightOnClick() {

            }
        });

        tv_oa_affirm.setOnClickListener(new OnViewClickListener() {
            @Override
            protected void singleClick(View view) {
                if (TextUtils.isEmpty(errorMsg)) {
                    getBuyData();
                } else {
                    ToastUtils.custom(errorMsg);
                }
            }
        });

        ///ETH不足弹框
        dialogHint.setOnDialogVersionListener(new DialogHint.OnDialogVersionListener() {
            @Override
            public void onSure() {
                //充值
                String weChatAccount = PreferencesUtil.getInstance().getString(OrderAffirmActivity.this, Constant.WECHAT_ACCOUNT);
                String accountU8 = CodeUtils.getInstance().str2Utf8(weChatAccount);
                List<ParamUtils.NameValue> parList = ParamUtils.build().put(WebActivity.TITLE, "ETH充值").put(WebActivity.URL, HttpConstant.RECHARGE_H5_URL + "?wechatAccount=" + accountU8).create();
                IntentUtils.startAty(OrderAffirmActivity.this, WebActivity.class, parList);
                finish();
            }

            @Override
            public void onCancel() {

            }
        });
    }


    /**
     * 获取数据
     */
    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        map.put("goodsId", mgcData.getRowId() + "");
        LKUtil.getHttpManager().postBody(HttpConstant.MAGIC_CAL_PRICE, map, handler);
    }

    /**
     * 获取算力信息的网络请求
     */
    @SuppressLint("HandlerLeak")
    public BaseHttpAsycResponceHandler<MagicCalBuyBean> handler = new BaseHttpAsycResponceHandler<MagicCalBuyBean>(true) {
        @SuppressLint("SetTextI18n")
        @Override
        public void onSuccess(MagicCalBuyBean data) {
            super.onSuccess(data);
            OrderAffirmActivity.this.buyData = data;
            String format = new DecimalFormat("###.#####").format(data.getGoodsPrice());
            tv_oa_price.setText("当前价格 " + format + "ETH");
        }

        @Override
        public void onFailed(int code, String message) {
            super.onFailed(code, message);

            ToastUtils.custom(message);
        }

        @Override
        public void onError() {
            super.onError();

        }
    };

    /**
     * 获取数据
     */
    private void getBuyData() {
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        map.put("goodsId", mgcData.getRowId() + "");
        map.put("ethRate", buyData.getEthRate() + "");
        map.put("goodsPrice", buyData.getGoodsPrice() + "");
        LKUtil.getHttpManager().postBody(HttpConstant.MAGIC_CAL_BUY, map, buyHandler);
    }

    /**
     * 获取算力信息的网络请求
     */
    @SuppressLint("HandlerLeak")
    public BaseHttpAsycResponceHandler<MagicCalDetailBean> buyHandler = new BaseHttpAsycResponceHandler<MagicCalDetailBean>(true) {
        @Override
        public void onSuccess(MagicCalDetailBean data) {
            super.onSuccess(data);
            ToastUtils.custom("购买成功");
            PreferencesUtil.getInstance().putInt(OrderAffirmActivity.this, Constant.BUY_CAL, (int) mgcData.getPowerNum());
            Intent intent = new Intent(OrderAffirmActivity.this, OrderDetailsActivity.class);
            intent.putExtra("ORDER_DATA", data);
            startActivity(intent);
            finish();
        }

        @Override
        public void onFailed(int code, String message) {
            super.onFailed(code, message);
            //保存错误信息
            if (code == -3) {
                dialogHint.setContent(message);
                dialogHint.setOkText("立即充值");
                dialogHint.show();
            } else {
                errorMsg = message;
                ToastUtils.custom(message);
            }
        }

        @Override
        public void onError() {
            super.onError();
            finish();
        }
    };


    /**
     * 设置界面数据
     *
     * @param data
     */
    @SuppressLint("SetTextI18n")
    private void setViewData(MagicCalShopBean data) {
        if (data == null) {
            return;
        }
        tv_oa_give.setText("首冲额外赠送" + df.format(data.getFirstGiveBgtNum()) + "BGT");
        tv_oa_title.setText(df.format(data.getPowerNum()) + "魔法算力  送" + df.format(data.getGiveBgtNum()) + "BGT");
        SpannableString text = MyTextUtils.getInstance().setAutoTextColor("有效期" + data.getValidTime() + "天", "[0-9]{1,}", "#FF5958");
        tv_oa_indate.setText(text);

        tv_oa_indate_time.setText(DateUtils.getBeforeDate(System.currentTimeMillis(), data.getValidTime()));
        tv_os_cal_num.setText("+" + df.format(data.getPowerNum()));
        tv_oa_bgt.setText("+" + df.format(data.getGiveBgtNum()));
        tv_oa_give_bgt.setText(df.format(data.getFirstGiveBgtNum()) + "BGT");
    }


}
